package com.security.test.handle;

import com.alibaba.fastjson.JSON;
import com.security.test.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.ServerResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author songmin.hou
 */
@Component
@Slf4j
public class MyFailurelHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.OK.value());
        String message = exception.getMessage();
        log.info("所属类为 === >> {},信息是 === >> {}", "MyFailurelHandler", message);
//        ServerResponse<String> serverResponse = ServerResponse.createByError(exception.getMessage());
        response.getWriter().write(JSON.toJSONString(R.fail(message)));
    }
}
